<template>
  <div class="PhoneCode">
    <van-field :value="form.phoneNo" @input="e=> {form.phoneNo = e.detail}" label="手机号:" placeholder="请输入手机号" required />
    <div class="code">
      <van-field
        :value="form.code"
        @input="e=> {form.code = e.detail}"
        name="验证码"
        placeholder="请输入验证码"
        label="验证码:"
        required />
    </div>
    <div class="code-btn">
      <van-button type="info" size="small" :disabled="codeBtnDisabled" @click="handleSendCode">{{ codeBtnVal }}</van-button>
    </div>
  </div>
</template>

<script>

import api from '@/api'
import Toast from '@/utils/Toast'

export default {
  props: {
    phoneNo: {
      type: String,
      default: '',
    },
  },
  data () {
    return {
      codeBtnVal: '发送验证码',
      codeBtnDisabled: false,
      form: {
        phoneNo: '',
        id: '',
        code: '',
      },
    }
  },
  watch: {
    phoneNo () {
      this.form.phoneNo = this.phoneNo
    },
  },
  methods: {
    async $submit () {
      await api.verifyCode({
        id: this.form.id,
        code: this.form.code,
      })
      return this.form.phoneNo
    },
    // 发送验证码
    async handleSendCode () {
      const phoneNo = this.form.phoneNo
      if (!phoneNo) {
        Toast('手机号不能为空')
        return
      }
      if (!/^(((13[0-9])|(14[5-7])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))+\d{8})$/.test(phoneNo)) {
        Toast('请输入正确手机号')
        return
      }
      this.codeBtnDisabled = true
      try {
        const data = await api.sendCode({ phoneNo: phoneNo })
        const res = data.result
        this.form.id = res
        var num = 59
        var timer = setInterval(() => {
          num--
          this.codeBtnVal = `${num}s`
          if (num === 0) {
            this.codeBtnDisabled = false
            clearInterval(timer)
            this.codeBtnVal = '发送验证码'
          }
        }, 1000)
      } catch (e) {
        this.codeBtnDisabled = false
      }
    },

  },
}
</script>

<style lang="scss" scoped> @import "~css/var.scss";
.PhoneCode {
  position: relative;
  background: #fff;
  /* in components-vant */
}
</style>
